// import { countryOptions} from './common.js'
// import {line_options} from './common.js'
// var obj_com = require('./common.js');
// console.log(countryOptions,900)
// console.log()
var $customerIntentionTable = $('#customerIntention');//客户分析表格
var clentXdata = [];
var memberXdata = [];

//防止表头与表格不对齐
$(window).resize(function () {
    $customerIntentionTable.bootstrapTable('resetView');
});

$(function () {

    timeComponentInit();
    clentXdata = getLastDays()
    memberXdata = getLastDays()


    userDataInit(clentXdata, memberXdata);//页面初始数据
    // LineInit('client',[],[],[],[],[])
    // LineInit('memberLine',[],[],[],[],[])
    customerIntentionInit("topMonth");//表格初始化
    // echartClientRate("clientRate",[1,2,3,4,5],[0,0,0,0,0],[0,0,0,0,0],"新增客户/成交客户",['新增客户', '成交客户'],'新增客户','成交客户')
    // //
    // echartClientRate("memberLine",[1,2,3,4,5],[0,0,0,0,0],[0,0,0,0,0],"续费会员/新单会员",['续费会员', '新单会员'],'续费会员','新单会员')
    // // echartmemberLine()
})

function queryUserData() {
    clentXdata = getLastDays()
    memberXdata = getLastDays()

    userDataInit(clentXdata, memberXdata);//页面初始数据
}


function timeComponentInit() {
    var endTime = new Date().FormatFMT("yyyy-MM")
    var startTime = GetPreMonthDay(new Date().FormatFMT("yyyy-MM"), 6)
    $('#startTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: startTime
    });
    $('#endTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: endTime
    });
}


function echartClientRate(id, xdata, ydata0, ydata1, title_text, legend_data, y_name0, y_name1) {
    //客户分析转化表
    let clientRate = document.getElementById(id)
    let myChart = echarts.init(clientRate);
    line_option.xAxis[0].data = xdata
    line_option.series[0].data = ydata0
    //
    line_option.series[1].data = ydata1
    line_option.title.text = title_text
    line_option.legend.data = legend_data
    line_option.series[0].name = y_name0
    line_option.series[1].name = y_name1


    myChart.setOption(line_option);
    window.onresize = myChart.resize;
    /**/
}

/**
 *页面数据初始化
 */
function userDataInit(xData, memberData) {
    var temp = {
        startDate: $("#startTm").val(),//
        endDate: $("#endTm").val()
    }
    $.ajax({
        url: '/customerController/superAdminAnalyseCustomer',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data:JSON.stringify(temp),
        success: (function (result) {
            if (result.code == '000000') {
                echartClientRate("memberLine", xData, result.data.renewalVipList, result.data.newVipList, "续费会员/新单会员", ['续费会员', '新单会员'], '续费会员', '新单会员')

                $('#member').text(result.data.vipProductMackCount);//会员产品成交
                $('#noMember').text(result.data.productMackCount);//非会员产品成交
                $('#addVip').text(result.data.makeAddVipCount);//会员新增
                $('#renew').text(result.data.renewalVip);//续费会员
                $('#maturity').text(result.data.expireVip);//到期会员
            }
        }),
        error: (function (res) {
            $.alert("加载失败");
        })
    })
}


/**
 *客户意向时间切换
 */
function customerIntentionSelectTime(time) {
    if (time == 'topMonth') {//本年
        $('.topMonth').addClass('active-second');
        $('.month').removeClass('active-second');
        $('.quarter').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("topMonth");
        customerIntentionInit("topMonth")

    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.topMonth').removeClass('active-second');
        $('.quarter').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("thisMonth");
        customerIntentionInit("thisMonth")
    }
    if (time == 'quarter') {//本季度
        $('.quarter').addClass('active-second');
        $('.month').removeClass('active-second');
        $('.topMonth').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("thisQuarter");
        customerIntentionInit("thisYear")
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.topMonth').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.quarter').removeClass('active-second');
        $("#dateType").val("thisYear");
        customerIntentionInit("thisQuarter")
    }
}

/**
 *客户转化时间切换
 */
function clientSelectTime(time) {
    if (time == 'topMonth') {//本年
        $('.clientTopMonth').addClass('active-second');
        $('.clentMonth').removeClass('active-second');
        $('.clientQuarter').removeClass('active-second');
        $('.clientYear').removeClass('active-second');
        $("#clientDataType").val("topMonth");
        $('#createTimeStart1').attr('disabled', false)
        $('#createTimeEnd1').attr('disabled', false)
        clentXdata = getLastDays()
        dataInit(clentXdata, memberXdata);//页面初始数据
        $(".detail-last").show()
    }
    if (time == 'month') {//本月
        $('.clentMonth').addClass('active-second');
        $('.clientTopMonth').removeClass('active-second');
        $('.clientQuarter').removeClass('active-second');
        $('.clientYear').removeClass('active-second');
        $("#clientDataType").val("thisMonth");
        $('#createTimeStart1').attr('disabled', true)
        $('#createTimeEnd1').attr('disabled', true)
        clentXdata = getDay()
        dataInit(clentXdata, memberXdata);
        $(".detail-last").show()
    }
    if (time == 'quarter') {//本季度
        $('.clientQuarter').addClass('active-second');
        $('.clentMonth').removeClass('active-second');
        $('.clientTopMonth').removeClass('active-second');
        $('.clientYear').removeClass('active-second');
        $("#clientDataType").val("thisQuarter");
        $('#createTimeStart1').attr('disabled', true)
        $('#createTimeEnd1').attr('disabled', true)
        clentXdata = getQuarterStartMonth()
        dataInit(clentXdata, memberXdata);
        $(".detail-last").hide()
    }
    if (time == 'year') {//本年
        $('.clientYear').addClass('active-second');
        $('.clientTopMonth').removeClass('active-second');
        $('.clentMonth').removeClass('active-second');
        $('.clientQuarter').removeClass('active-second');
        $("#clientDataType").val("thisYear");
        $('#createTimeStart1').attr('disabled', true)
        $('#createTimeEnd1').attr('disabled', true)
        clentXdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        dataInit(clentXdata, memberXdata)
        $(".detail-last").hide()
    }
}


/**
 *会员转化时间切换
 */
function memberSelectTime(time) {
    if (time == 'topMonth') {//本年
        $('.memberTopMonth').addClass('active-second');
        $('.memberMonth').removeClass('active-second');
        $('.memberQuarter').removeClass('active-second');
        $('.memberYear').removeClass('active-second');
        $("#memberDateType").val("topMonth");
        $('#createTimeStart').attr('disabled', false)
        $('#createTimeEnd').attr('disabled', false)
        memberXdata = getLastDays()
        dataInit(clentXdata, memberXdata);
        $(".detail-last-regin").show()
    }
    if (time == 'month') {//本月
        $('.memberMonth').addClass('active-second');
        $('.memberTopMonth').removeClass('active-second');
        $('.memberQuarter').removeClass('active-second');
        $('.memberYear').removeClass('active-second');
        $("#memberDateType").val("thisMonth");
        $('#createTimeStart').attr('disabled', true)
        $('#createTimeEnd').attr('disabled', true)
        memberXdata = getDay()
        dataInit(clentXdata, memberXdata);
        $(".detail-last-regin").show()
    }
    if (time == 'quarter') {//本季度
        $('.memberQuarter').addClass('active-second');
        $('.memberMonth').removeClass('active-second');
        $('.memberTopMonth').removeClass('active-second');
        $('.memberYear').removeClass('active-second');
        $("#memberDateType").val("thisQuarter");
        $('#createTimeStart').attr('disabled', true)
        $('#createTimeEnd').attr('disabled', true)
        memberXdata = getQuarterStartMonth()
        dataInit(clentXdata, memberXdata);
        $(".detail-last-regin").hide()
    }
    if (time == 'year') {//本年
        $('.memberYear').addClass('active-second');
        $('.memberTopMonth').removeClass('active-second');
        $('.memberMonth').removeClass('active-second');
        $('.memberQuarter').removeClass('active-second');
        $("#memberDateType").val("thisYear");
        $('#createTimeStart').attr('disabled', true)
        $('#createTimeEnd').attr('disabled', true)
        memberXdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        dataInit(clentXdata, memberXdata)
        $(".detail-last-regin").hide()
    }
}

/**
 *客户分析表格初始化
 */
function customerIntentionInit(dateType) {
    //先销毁表格
    $customerIntentionTable.bootstrapTable('destroy');
    $customerIntentionTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerController/getAnalyseCustomerIntention',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        // pageSize: 10,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        queryParams: {
            dateType: dateType
        },//查询参数
        columns: [
            {title: '客户类型', field: 'name', align: 'center', valign: 'middle'},
            {title: '客户数量', field: 'value', align: 'center', valign: 'middle'},
            {title: '类型占比', field: 'percentage', align: 'center', valign: 'middle'},
            {title: '占比数量', field: 'percentageValue', align: 'center', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'center', events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var data = [
                    {
                        name: '意向客户',
                        value: result.data.intentionCustomerCount,
                        percentage: '意向占比',
                        percentageValue: result.data.intentionCustomerRatio
                    },
                    {
                        name: '有预算客户',
                        value: result.data.budgetCustomerCount,
                        percentage: '预算占比',
                        percentageValue: result.data.budgetCustomerRatio
                    },
                    {
                        name: '跟进客户',
                        value: result.data.followCustomerCount,
                        percentage: '跟进占比',
                        percentageValue: result.data.followCustomerRatio
                    },
                    {
                        name: '竞对客户',
                        value: result.data.rivalCustomerCount,
                        percentage: '竞对占比',
                        percentageValue: result.data.rivalCustomerRatio
                    },
                    {
                        name: '流失客户',
                        value: result.data.outCustomerCount,
                        percentage: '流失占比',
                        percentageValue: result.data.outCustomerRatio
                    },
                ]
                var obj = {
                    "rows": data,
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    return [
        '<a type="button" id="detail" class="btn btn-xs btn-default m-r-5 show-btn" title="查看分析" data-toggle="tooltip"">查看分析</a>',
    ].join('');
}

window.operateEvents = {}

//获取上月天数
function getLastDays() {
    var now = new Date;
    now.setMonth(now.getMonth() - 1);
    now.setDate(1);
    var next = new Date;
    next.setDate(1);
    var arr = [];
    while (now < next) {
        arr.push(now.getDate());
        now.setDate(now.getDate() + 1);
    }
    return arr;
}

//获取本季度
function getQuarterStartMonth() {
    var now = new Date(); //当前日期
    var nowMonth = now.getMonth(); //当前月
    var quarterStartMonth = 0;
    if (nowMonth < 3) {
        quarterStartMonth = [1, 2, 3];
    }
    if (2 < nowMonth && nowMonth < 6) {
        quarterStartMonth = [4, 5, 6];
    }
    if (5 < nowMonth && nowMonth < 9) {
        quarterStartMonth = [7, 8, 9];
    }
    if (nowMonth > 8) {
        quarterStartMonth = [10, 11, 12];
    }
    return quarterStartMonth;
}

//获取本月
function getDay() {
    var now = new Date(); //当前日期
    var nowDay = now.getDate(); //当前日
    var dayData = [];
    for (var i = 0; i < nowDay; i++) {
        dayData.push(i + 1)
    }
    return dayData
}

/**
 * 折线图初始化
 */
// function LineInit(id,title,nameData,xData,data,data1){
//     let dom = document.getElementById(id);
//     let myChart = echarts.init(dom);
//     let option = {
//         // title: {
//         //     text: title
//         // },
//         tooltip: {
//             trigger: 'axis'
//         },
//         legend: {
//             data: nameData
//         },
//         xAxis: {
//             type: 'category',
//             data:xData,
//             boundaryGap: false,
//         },
//         yAxis: {
//             type: 'value',
//         },
//         series: [
//             {
//                 name:nameData[0],
//                 data: data,
//                 type: 'line'
//             },
//             {
//                 name:nameData[1],
//                 data: data1,
//                 type: 'line'
//             },
//         ]
//     };
//     myChart.setOption(option);
//     window.addEventListener("resize",function(){
//         myChart.resize();
//     });
// }


//折线


// const color = ['#6A8ED8', '#1BC8B4']
const color = ['#6699ff', "#52cca3", '#caed8b']
var line_option = {

    title: {
        text: '新增客户/成交客户',
        left: '2%',
        top: '3%',
        textStyle: {
            color: '#999999',
            fontSize: '12',
        },
    },
    tooltip: {
        trigger: 'axis',
        extraCssText: 'font-size:14px;line-height:24px;color:#fff;background:#212947;opacity: 0.9;padding:10px 20px;box-shadow:0 0 3px rgba(0, 0, 0, 0.2)',
        formatter: function (params) {
            let html = `<span style="">${params[0].axisValue}</span>`
            params.forEach(v => {
                html += `<div>
<span style="display:inline-block;color: #999999;margin-right:5px;border-radius:10px;width:10px;height:10px;border: 2px solid #FFFFFF;background-color:${color[v.componentIndex]};"></span>
${v.seriesName}

<span style="color:${color[v.componentIndex]};font-size:18px;font-weight:700;padding-left: 10px;">${v.value}</span>`
            })
            return html
        }
    },
    legend: {
        data: ['新增客户', '成交客户'],
        top: '0%',
        right: '2%',
        // textStyle: {
        //     fontSize:16,
        //     color: '#8597c1'
        // }
    },

    xAxis: [{
        show: true,
        type: 'category',
        axisLine: {
            show: true,
            lineStyle: {
                color: 'rgba(83, 83, 83,0.1)',
            },


        },
        axisTick: {//坐标轴刻度相关设置。
            show: false,
        },
        splitArea: {
            // show: true,
            color: '#f00',
            lineStyle: {
                color: '#f00'
            },
        },
        axisLabel: {
            color: '#999999',
            margin: 20
        },
        splitLine: {
            show: false
        },
        boundaryGap: false,
        data: [],

    }],
    grid: {

        left: '5%',
        right: "5%",
        borderWidth: 1
    },
    yAxis: [{
        name: '',
        type: 'value',
        min: 0,
        // max: 140,
        splitNumber: 4,
        splitLine: {
            //分隔线
            show: false,
            lineStyle: {
                //坐标轴在 grid 区域中的分隔线。
                color: 'rgba(83, 83, 83,0.1)'
            }
        },
        axisLine: {
            //坐标轴轴线相关设置
            show: true,
            lineStyle: {
                color: 'rgba(83, 83, 83,0.1)',
            },
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: '#999999',
            },
            margin: 20
        },
        axisTick: {
            show: false,
        },
    }],
    series: [{
        name: '新增客户',
        type: 'line',
        smooth: true, //是否平滑
        showAllSymbol: false,
        symbol: 'circle',
        symbolSize: 2,
        lineStyle: {
            normal: {
                color: "#6699ff",
                width: 0,
            },
        },
        itemStyle: {
            color: "#6699ff",

        },
        areaStyle: {
            normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: 'rgba(102, 153, 255, .8)' //rgba(61, 127, 255, 1) //rgba(106, 142, 216, .5)
                },
                    {
                        offset: 1,
                        color: 'rgba(102, 153, 255, .8)'
                    }
                ], false),
                shadowColor: 'rgba(102, 153, 255, 0.9)',
                shadowBlur: 20
            }
        },
        data: []
    },
        {
            name: '成交客户',
            type: 'line',
            smooth: true, //是否平滑
            showAllSymbol: false,
            symbol: 'circle',
            symbolSize: 2,
            lineStyle: {
                normal: {
                    color: "#52cca3",
                    width: 0,
                },
            },
            itemStyle: {
                color: "#52cca3",
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(82, 204, 163, .8)'
                    },
                        {
                            offset: 1,
                            color: 'rgba(82, 204, 163,.8)'
                        }
                    ], false),
                    shadowColor: 'rgba(82, 204, 163, 0.9)',
                    shadowBlur: 20
                }
            },
            data: []
        },


    ]
};

